<?php
namespace app\controller;

use app\BaseController;


use app\model\UserMsg;
use app\Request;
use think\facade\Db;

use think\facade\View;

class Users extends BaseController
{
    public function detail()
    {
        $user = session('user');
        $res = UserMsg::where(['id'=>$user['id']])->find();
        return view('users/detail',['data'=>$res]);
    }
    public function update()
    {
        return view('users/update');
    }


    // 执行提交表单
    public function doSubmitDetail(Request $request)
    {
        $user = session('user');
        $input = $request->all();

        $res = UserMsg::where(['username'=>$input['username']])->find();
        if(!$res || $user['username'] == $input['username']){
            $res = UserMsg::where(['id'=>$user['id']])->update($input);
            $data = ['msg'=>'更新成功','code'=>200];
        }else{
            $data = ['msg'=>'当前帐号已经被使用','code'=>403];
        }

        return json($data);
    }

    // 执行提交修改密码
    public function doSubmitUpdate(Request $request)
    {
        $user = session('user');
        $input = $request->all();

        $res = UserMsg::where(['id'=>$user['id']])->find();
        if($res){
            // 检测密码
            if(password_verify($input['old_password'],$res['password'])){
                // 密码加密
                $input['new_password'] = password_hash($input['new_password'],PASSWORD_DEFAULT);
                $res = UserMsg::where(['id'=>$user['id']])->update(['password'=>$input['new_password']]);
                $data = ['msg'=>'更新成功','code'=>200];
            }else{
                $data = ['msg'=>'密码错误','code'=>403];
            }
        }else{
            $data = ['msg'=>'帐号不存在','code'=>403];
        }

        return json($data);
    }
}
